package com.reggie.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.ResultResponseVo;
import com.reggie.common.enums.front.LoginEnum;
import com.reggie.module.entity.dto.userDto.LoginDto;
import com.reggie.module.entity.po.User;
import com.reggie.module.mapper.UserMapper;
import com.reggie.module.service.UserService;
import com.reggie.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.reggie.common.Constant.*;

/**
 * @Author 早睡蛋
 * @Date 2022/9/26 20:39:43
 * @Desc:
 */
@Service
@Slf4j
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 用户登录/注册
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResultResponseVo login(LoginDto loginDto, HttpServletRequest request) {
        //1.检查验证码是否正确
        String phone = loginDto.getPhone();
        String redisCode = redisUtil.getString(REGISTER_CODE + phone);
        if (redisCode == null) {
            return LoginEnum.MSM_FAIL.getResultResponseVo();
        }
        if (!redisCode.equals(loginDto.getCode())) {
            return LoginEnum.MSM_FAIL.getResultResponseVo();
        }
        //2.检查数据库是否有该用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("id", "phone").eq("phone", phone);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            user = new User(phone,1);
            log.info("user={}", user);
            userMapper.insert(user);
        }
        request.getSession().setAttribute(USER_SESSION, user.getId());
        return LoginEnum.LOGIN_OK.getResultResponseVo();
    }
}
